package com.example.nio.three;

import java.io.IOException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * @Description
 * @Author 26233
 * @Create 2021-10-28 17:10:15
 */

public class AcceptSelectorThread implements Runnable {

    private Selector acceptSelector;

    public AcceptSelectorThread(Selector selector) {
        this.acceptSelector = selector;
    }

    @Override
    public void run() {
        System.out.println("accept thread start");
        while (true){
            try {
                acceptSelector.select();
                Set<SelectionKey> selectionKeys = acceptSelector.selectedKeys();
                Iterator<SelectionKey> iterator = selectionKeys.iterator();
                while (iterator.hasNext()){
                    SelectionKey selectionKey = iterator.next();
                    iterator.remove();
                    try{
                        if (selectionKey.isValid()){
                            if (selectionKey.isAcceptable()){

                                System.out.println("accept");
                                ServerSocketChannel acceptChannel = (ServerSocketChannel) selectionKey.channel();
                                SocketChannel client = acceptChannel.accept();
                                if (client != null){
                                    client.configureBlocking(false);

                                    System.out.println(Thread.currentThread() + " accept ");
                                    client.register(acceptSelector, SelectionKey.OP_READ);
                                }
//                                if (selectorIndex > 3){
//                                    selectorIndex = 0;
//                                }
//                                selectors[selectorIndex].wakeup();
//                                client.register(selectors[selectorIndex++], SelectionKey.OP_READ);

                            }else{
                                System.out.println("key is not accept");
                            }
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                        selectionKey.channel().close();
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
